package com.leimo.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化工具类
 * @author 夏智峰
 * @create 2018-02-07 17:00
 */
public class ObjectUtil {
  /**
   * 对象转byte[]
   */
  public static byte[] objectToBytes(Object object) throws IOException {
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    ObjectOutputStream oo = new ObjectOutputStream(bo);
    oo.writeObject(object);
    byte[] bytes = bo.toByteArray();
    bo.close();
    oo.close();
    return bytes;
  }

  /**
   * byte[]转对象
   */
  public static Object bytesToObject(byte[] bytes) throws Exception{
    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
    ObjectInputStream sIn = new ObjectInputStream(in);
    return sIn.readObject();
  }
}
